<?php
/**
* Numedia Studio Framework
* 
* Admin interface creator.
*
* This is called by the theme "init_admin.php"
*/


/**
 * Tell WordPress to run ns_add_admin() when the 'admin_menu' hook is run.
 */
add_action( 'admin_menu', 'ns_add_admin' );

if ( ! function_exists( 'ns_add_admin' ) ):
/**
 * Builds the administration menu and pages
 *
 * @since Twenty Eleven 1.0
 */
function ns_add_admin() {

    global $query_string;
    global $current_user;


   	// Reset the settings, sanitizing the various requests made.
   	// Use a SWITCH to determine which settings to update.

   	/* Make sure we're making a request.
   	------------------------------------------------------------*/

   	if ( isset( $_REQUEST['page'] ) ) {

   		// Sanitize page being requested.
   		$_page = '';

		$_page = mysql_real_escape_string( strtolower( trim( strip_tags( $_REQUEST['page'] ) ) ) );

		// Sanitize action being requested.
   		$_action = '';

		if ( isset( $_REQUEST['ns_save'] ) ) {
			$_action = mysql_real_escape_string( strtolower( trim( strip_tags( $_REQUEST['ns_save'] ) ) ) );

		} // End IF Statement
		
		// If the action is "reset", run the SWITCH.

		/* Perform settings reset.
  		------------------------------------------------------------*/

		if ( $_action == 'reset' ) {

			// Add nonce security check.
			if ( function_exists( 'check_ajax_referer' ) ) {
				check_ajax_referer( 'wooframework-theme-options-reset', '_ajax_nonce' );
			} // End IF Statement
			
			switch ( $_page ) {

				case 'ns':

					$options =  ns_get_option();
					
					// Reset options
					ns_reset_options($options,'ns' );
					
					//header( "Location: admin.php?page=ns&reset=true" );
					//die;

				break;

			} // End SWITCH Statement

		} // End IF Statement

   	} // End IF Statement
	
	
	// add main menu
    if(function_exists( 'add_object_page'))
    {
        add_object_page ( 'Numedia Studio Framework', ns_theme_name, 'manage_options','ns', 'ns_output_admin_html', $icon);
    }
    else
    {
        add_menu_page('Numedia Studio Framework', ns_theme_name, 'manage_options', 'ns_home', 'ns_output_admin_html', ns_icon);
    }
    $nspage = add_submenu_page( 'ns', ns_theme_name, 'Theme Options', 'manage_options', 'ns','ns_output_admin_html' ); // Default
	
	// attach scripts to the head
	add_action( "admin_print_scripts-$nspage", 'ns_load_scripts' );
	
}
endif; // ns_add_admin



if ( ! function_exists( 'ns_output_admin_html' ) ):
/**
 * Builds the administration menu and pages
 *
 * @since Twenty Eleven 1.0
 */
function ns_output_admin_html() {
	$options =  ns_get_option();
	?>
<div class="wrap" id="ns_container">
<div id="woo-popup-save" class="woo-save-popup"><div class="woo-save-save"><?php _e( 'Options Updated', ns_text_domaine); ?></div></div>
<div id="woo-popup-reset" class="woo-save-popup"><div class="woo-save-reset"><?php _e( 'Options Reset', ns_text_domaine); ?></div></div>
    <form action="" enctype="multipart/form-data" id="wooform">
    <?php
    	// Add nonce for added security.
    	if ( function_exists( 'wp_nonce_field' ) ) { wp_nonce_field( 'wooframework-theme-options-update' ); } // End IF Statement

    	$ns_nonce = '';

    	if ( function_exists( 'wp_create_nonce' ) ) { $ns_nonce = wp_create_nonce( 'wooframework-theme-options-update' ); } // End IF Statement

    	if ( $ns_nonce == '' ) {} else {

    ?>
    	<input type="hidden" name="_ajax_nonce" value="<?php echo $ns_nonce; ?>" />
    <?php

    	} // End IF Statement
    ?>
        <div id="header">
           <div class="logo">
				<?php if(get_option( 'framework_ns_backend_header_image')) { ?>
                <img alt="" src="<?php echo get_option( 'framework_ns_backend_header_image' ); ?>"/>
                <?php } else { ?>
                <img alt="ns" src="<?php echo ns_admin_path; ?>/images/logo.png"/>
                <?php } ?>
            </div>
             <div class="theme-info">
				<span class="theme">Numedia Studio</span>
				<span class="framework">Framework <?php echo ns_version; ?></span>
			</div>
			<div class="clear"></div>
		</div>
        <?php
		// Rev up the Options Machine
       $return = apply_filters('ns_before_option_page', ns_options_parser($options));
        ?>
		<div id="support-links">
			<ul>
				<li class="forum"><a href="http://numediastudio.com" target="_blank">Visit Numedia Studio</a></li>
                <li class="right"><img style="display:none" src="<?php echo ns_admin_path; ?>/images/loading-top.gif" class="ajax-loading-img ajax-loading-img-top" alt="Working..." /><a href="#" id="expand_options">[+]</a> <input type="submit" value="Save All Changes" class="button submit-button" /></li>
			</ul>
		</div>
        <div id="main">
	        <div id="woo-nav">
				<ul>
					<?php echo $return[1] ?>
				</ul>
			</div>
			<div id="content">
	         <?php echo $return[0]; /* Settings */ ?>
	        </div>
	        <div class="clear"></div>

        </div>
        <div class="save_bar_top">
        <img style="display:none" src="<?php echo ns_admin_path; ?>/images/loading-bottom.gif" class="ajax-loading-img ajax-loading-img-bottom" alt="Working..." />
        <input type="submit" value="Save All Changes" class="button submit-button" />
        </form>

        <form method="post" style="display: inline;" id="wooform-reset">
        <?php
	    	// Add nonce for added security.
	    	if ( function_exists( 'wp_nonce_field' ) ) { wp_nonce_field( 'wooframework-theme-options-reset' ); } // End IF Statement

	    	$ns_nonce = '';

	    	if ( function_exists( 'wp_create_nonce' ) ) { $ns_nonce = wp_create_nonce( 'wooframework-theme-options-reset' ); } // End IF Statement

	    	if ( $ns_nonce == '' ) {} else {

	    ?>
	    	<input type="hidden" name="_ajax_nonce" value="<?php echo $ns_nonce; ?>" />
	    <?php

	    	} // End IF Statement
	    ?>
            <span class="submit-footer-reset">
            <input name="reset" type="submit" value="Reset All Options" class="button submit-button reset-button" onclick="return confirm( 'Click OK to reset all options. All settings will be lost!' );" />
            <input type="hidden" name="ns_save" value="reset" />
            </span>
        </form>

        </div>
        <?php  if (!empty($update_message)) echo $update_message; ?>

<div style="clear:both;"></div>
</div><!--wrap-->

 <?php
}
endif; // ns_output_admin_html


if ( ! function_exists( 'ns_load_scripts' ) ):
/**
 * Loads jquery and other scripts to the header of the pages
 *
 * @since Twenty Eleven 1.0
 */
function ns_load_scripts() {
	
	add_action( 'admin_head', 'ns_admin_head' );
		function ns_admin_head() {
		// include style ?>
		<link rel="stylesheet" media="screen" type="text/css" href="<?php echo ns_admin_path; ?>/css/style.css" />
		<script type="text/javascript">
		jQuery(document).ready(function(){

				// Create sanitary variable for use in the JavaScript conditional.
				<?php

				$is_reset = 'false';

				if( isset( $_REQUEST['reset'] ) ) {

					$is_reset = $_REQUEST['reset'];

					$is_reset = strtolower( strip_tags( trim( $is_reset ) ) );

				} else {

					$is_reset = 'false';

				} // End IF Statement

				?>

				if( '<?php echo $is_reset; ?>' == 'true'){

					var reset_popup = jQuery( '#woo-popup-reset' );
					reset_popup.fadeIn();
					window.setTimeout(function(){
						   reset_popup.fadeOut();
						}, 2000);
						//alert(response);

				}

			//Update Message popup
			jQuery.fn.center = function () {
				this.animate({"top":( jQuery(window).height() - this.height() - 200 ) / 2+jQuery(window).scrollTop() + "px"},100);
				this.css( "left", 250 );
				return this;
			}


			jQuery( '#woo-popup-save').center();
			jQuery( '#woo-popup-reset').center();
			jQuery(window).scroll(function() {

				jQuery( '#woo-popup-save').center();
				jQuery( '#woo-popup-reset').center();

			});

			//String Builder Details
			jQuery( '.string_builder_return').each(function(){

				var top_object = jQuery(this);
				if(jQuery(this).children( '.string_option').length == 0){
					top_object.find( '.string_builder_empty').show();
				}

			})
				
			//AJAX Remove (clear option value)
			jQuery( '.string_option .delete').click(function(){

alert('submited');
					<?php // Nonce Security ?>
					<?php if ( function_exists( 'wp_create_nonce' ) ) { $ns_nonce = wp_create_nonce( 'wooframework-theme-options-update' ); } // End IF Statement ?>

					var id = jQuery(this).parent().parent().parent().attr( 'id' );
					var name = jQuery(this).attr( 'rel' );
					var data = 'id='+id+'&name='+name;

					var ajax_url = '<?php echo admin_url( "admin-ajax.php" ); ?>';
					var data = {
						action: 'ns_ajax_post_action',
						type: 'string_builder_delete',
						data: data,
						_ajax_nonce: '<?php echo $ns_nonce; ?>'
					};

					jQuery.post(ajax_url, data, function(response) {
						jQuery( '#string_builer_option_'+response).fadeOut( 'slow',function(){jQuery(this).remove();});
					});
					return false;

				});

			//Save everything else
			jQuery( '#wooform').submit(function(){
					function newValues() {
					  var serializedValues = jQuery( "#wooform *").not( '.woo-ignore').serialize();
					  return serializedValues;
					}
					jQuery( ":checkbox, :radio").click(newValues);
					jQuery( "select").change(newValues);
					jQuery( '.ajax-loading-img').fadeIn();
					var serializedReturn = newValues();

					var ajax_url = '<?php echo admin_url( "admin-ajax.php" ); ?>';

					 //var data = {data : serializedReturn};
					var data = {
						<?php if(isset($_REQUEST['page']) && $_REQUEST['page'] == 'ns'){ ?>
						type: 'options',
						<?php } ?>
						action: 'ns_ajax_post_action',
						data: serializedReturn,

						<?php // Nonce Security ?>
						<?php if ( function_exists( 'wp_create_nonce' ) ) { $ns_nonce = wp_create_nonce( 'wooframework-theme-options-update' ); } // End IF Statement ?>

						_ajax_nonce: '<?php echo $ns_nonce; ?>'
					};
					
					jQuery.post(ajax_url, data, function(response) {

						var success = jQuery( '#woo-popup-save' );
						var loading = jQuery( '.ajax-loading-img' );
						loading.fadeOut();
						success.fadeIn();
						console.log(response);
						window.setTimeout(function(){
						   success.fadeOut();


						}, 2000);
					});

					return false;

				});

		});
		</script>

<?php
	} // ns_admin_head
}
endif; // ns_load_scripts



add_action( 'wp_ajax_ns_ajax_post_action', 'ns_ajax_callback' );

if (!function_exists( 'ns_ajax_callback')) {
function ns_ajax_callback() {

	// check security with nonce.
	if ( function_exists( 'check_ajax_referer' ) ) { check_ajax_referer( 'wooframework-theme-options-update', '_ajax_nonce' ); } // End IF Statement

	global $wpdb; // this is how you get access to the database

	$save_type = $_POST['type'];

	//Uploads
	if($save_type == 'upload'){

		$clickedID = $_POST['data']; // Acts as the name
		$filename = $_FILES[$clickedID];
       	$filename['name'] = preg_replace( '/[^a-zA-Z0-9._\-]/', '', $filename['name']);

       	//print_r($filename);

		$override['test_form'] = false;
		$override['action'] = 'wp_handle_upload';
		$uploaded_file = wp_handle_upload($filename,$override);

				$upload_tracking[] = $clickedID;
				update_option( $clickedID , $uploaded_file['url'] );

		 if(!empty($uploaded_file['error'])) {echo 'Upload Error: ' . $uploaded_file['error']; }
		 else { echo $uploaded_file['url']; } // Is the Response
	}
	elseif($save_type == 'image_reset'){

			$id = $_POST['data']; // Acts as the name
			delete_option($id);
	}
	elseif($save_type == 'string_builder_add'){
		$data = $_POST['data'];
		parse_str($data,$output);

		$id = $output['id'];
		$name = $output['name'];
		$name = preg_replace( '/[^a-zA-Z0-9-_ ]/i','',$name);
		$value = stripslashes($output['value']);
		$value = stripslashes($value);
		$return = "$id|$name|$value";
		echo $return;

		$option_temp = get_option($id);
		$option_temp[$name] = $value;

		update_option($id,$option_temp);

	}
	elseif($save_type == 'string_builder_delete'){
		$data = $_POST['data'];
		parse_str($data,$output);

		$id = $output['id'];
		$name = $output['name'];
		echo str_replace( " ","_",$name);
		$option_temp = get_option($id);
		unset($option_temp[$name]);
		update_option($id,$option_temp);

	}
	elseif ($save_type == 'options' OR $save_type == 'seo' OR $save_type == 'tumblog' OR $save_type == 'framework') {
		$data = $_POST['data'];
		parse_str($data,$output);

		// Remove the "ns_save" item from the output array.
		if ( isset( $output['ns_save'] ) && $output['ns_save'] == 'reset' ) { unset( $output['ns_save'] ); }

		$data = stripslashes( $data ); // Remove slashes from the serialised string.

		//Pull options
        $options =  ns_get_option();


		foreach($options as $option_array){

			if(isset($option_array['id'])){
				$id = $option_array['id'];
			} else { $id = null;}
			$old_value = get_option($id);
			$new_value = '';

			if(isset($output[$id])){
				$new_value = $output[$option_array['id']];
			}

			if(isset($option_array['id'])) { // Non - Headings...

				//Import of prior saved options
				if($id == 'framework_ns_import_options'){

					//Decode and over write options.
					$new_import = base64_decode($new_value);
					$new_import = unserialize($new_import);

					//echo '<pre>';
					//print_r($new_import);
					//echo '</pre>';
					if(!empty($new_import)) {
						foreach($new_import as $id2 => $value2){
							if(is_serialized($value2)) {
								update_option($id2,unserialize($value2));
							} else {
								update_option($id2,$value2);
							}
						}
					}

				} else {

					$type = $option_array['type'];

					if ( is_array($type)){
						foreach($type as $array){
							if($array['type'] == 'text'){
								$id = $array['id'];
								$std = $array['std'];
								$new_value = $output[$id];
								if($new_value == ''){ $new_value = $std; }

								update_option( $id, stripslashes($new_value));
							}
						}
					}
					elseif ( $type == 'text' && $save_type == 'seo' ) { // Text Save

						$new_value = $output[$id];
						if( $new_value == '' && $std != '' ){ $new_value = $std; }

						$new_value = stripslashes( stripslashes( $new_value ) );

						update_option( $id, $new_value );
					}
					elseif($new_value == '' && $type == 'checkbox'){ // Checkbox Save

						update_option($id,'false' );
					}
					elseif ($new_value == 'true' && $type == 'checkbox'){ // Checkbox Save

						update_option($id,'true' );
					}
					elseif($type == 'multicheck'){ // Multi Check Save

						$option_options = $option_array['options'];

						foreach ($option_options as $options_id => $options_value){

							$multicheck_id = $id . "_" . $options_id;

							if(!isset($output[$multicheck_id])){
							  update_option($multicheck_id,'false' );
							}
							else{
							   update_option($multicheck_id,'true' );
							}
						}
					}
					elseif($type == 'typography'){

						$typography_array = array();

						$typography_array['size'] = $output[$option_array['id'] . '_size'];

						$typography_array['unit'] = $output[$option_array['id'] . '_unit'];

						$typography_array['face'] = stripslashes($output[$option_array['id'] . '_face']);

						$typography_array['style'] = $output[$option_array['id'] . '_style'];

						$typography_array['color'] = $output[$option_array['id'] . '_color'];

						update_option($id,$typography_array);

					}
					elseif($type == 'border'){

						$border_array = array();

						$border_array['width'] = $output[$option_array['id'] . '_width'];

						$border_array['style'] = $output[$option_array['id'] . '_style'];

						$border_array['color'] = $output[$option_array['id'] . '_color'];

						update_option($id,$border_array);

					}
					elseif($type != 'upload_min'){

						update_option($id,stripslashes($new_value));
					}
				}
			}
		}
	}


	if( $save_type == 'options' OR $save_type == 'framework' ){
		/* Create, Encrypt and Update the Saved Settings */
		$ns_options = array();
		$data = array();
		if($save_type == 'framework' ){
			$options =  ns_get_option();
		}
		$count = 0;
		foreach($options as $option){
			if(isset($option['id'])){
				$count++;
				$option_id = $option['id'];
				$option_type = $option['type'];

				if(is_array($option_type)) {
					$type_array_count = 0;
					foreach($option_type as $inner_option){
						$option_id = $inner_option['id'];
						if ( isset( $data[$option_id] ) )
							$data[$option_id] .= get_option($option_id);
						else
							$data[$option_id] = get_option($option_id);
					}
				}
				else {
					$data[$option_id] = get_option($option_id);
				}
			}
		}

		$output = "<ul>";

		foreach ($data as $name => $value){

				if(is_serialized($value)) {

					$value = unserialize($value);
					$ns_array_option = $value;
					$temp_options = '';
					foreach($value as $v){
						if(isset($v))
							$temp_options .= $v . ',';

					}
					$value = $temp_options;
					$ns_array[$name] = $ns_array_option;
				} else {
					$ns_array[$name] = $value;
				}

				$output .= '<li><strong>' . $name . '</strong> - ' . $value . '</li>';
		}
		$output .= "</ul>";
		$output = base64_encode($output);

		update_option( 'ns_options',$ns_array);
		update_option( 'ns_settings_encode',$output);

	}

  die();

}
}
?>